#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/select.h>
#include <errno.h>

#define MAX_FD 6
#define STDIN_INDEX 0
#define SERVER_FD_INDEX 1
#define CLIENT_FD_BEGIN_INDEX 2
#define BUFFER_SIZE 1024
#define PORT 8080

int setup_tcp_server_socket(const char *ip, int port) {
    int sockfd;
    struct sockaddr_in servaddr;

    // 创建socket
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }
    int opt = 1;
    // 设置套接字选项，允许端口重用
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("Setsockopt failed");
        return -1;
    }
    memset(&servaddr, 0, sizeof(servaddr));

    // 为服务器填充地址结构
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(port);

    // 绑定socket到本地地址
    if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("Bind failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    // 监听连接请求
    if (listen(sockfd, 5) < 0) {
        perror("Listen failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    return sockfd;
}

int main() {
    int max_fd, fd, activity, valread, server_fd, client_fd;
    int socks[MAX_FD] = {0,};
    struct sockaddr_in address;
    socklen_t addrlen = sizeof(address);
    char buffer[BUFFER_SIZE];
    fd_set readfds;
    memset(socks, -1, sizeof(socks)*MAX_FD);
    // 设置服务器socket
    server_fd = setup_tcp_server_socket("localhost", PORT);
    socks[STDIN_INDEX] = STDIN_FILENO; // 标准输入
    socks[SERVER_FD_INDEX] = server_fd; // 服务器socket

    // 初始化最大文件描述符
    max_fd = server_fd;

    while (1) {
        // 清零文件描述符集合
        FD_ZERO(&readfds);

        // 添加需要监控的文件描述符
        for(fd = 0 ; fd < MAX_FD ; fd++)
            if (socks[fd] != -1)
                FD_SET(socks[fd], &readfds);

        // 设置超时时间，NULL表示永远等待
        struct timeval timeout = {10, 50000}; // 10.05秒超时 50000微妙
        activity = select(max_fd + 1, &readfds, NULL, NULL, &timeout);

        if ((activity < 0) && (errno!=EINTR)) {
            printf("Select error");
        }

        // 检查标准输入是否有数据可读
        if (FD_ISSET(STDIN_FILENO, &readfds)) {
            // 从标准输入读取数据
            fgets(buffer, BUFFER_SIZE, stdin);
            // 这里可以处理读取到的数据，例如发送到客户端
            printf("Read from stdin: %s", buffer);
        }

        // 检查服务器socket是否有新连接请求
        if (FD_ISSET(server_fd, &readfds)) {
            // 接受新的连接请求
            if ((client_fd = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
                perror("Accept failed");
                continue;
            }
            printf("New connection, socket fd = %d, IP = %s, port = %d\n", client_fd, inet_ntoa(address.sin_addr), ntohs(address.sin_port));

            // 将新连接的socket添加到监控列表中
            for(fd = 2 ; fd < MAX_FD ; fd++)
                if (socks[fd] == -1) {
                    socks[fd] = client_fd;
                    break;
                }
            if (fd == MAX_FD) {
                printf("Too many clients, max reached\n");
                exit(0);
            }
            if (client_fd > max_fd)
                max_fd = client_fd;
        }

        // 检查每个已连接的客户端socket是否有数据可读
        for(fd = CLIENT_FD_BEGIN_INDEX ; fd < MAX_FD ; fd++)
            if (socks[fd] != -1 && FD_ISSET(socks[fd], &readfds)) {
                // 读取并处理来自客户端的数据
                valread = read(socks[fd], buffer, BUFFER_SIZE);
                if (valread == 0) {
                    // 客户端关闭了连接
                    getpeername(socks[fd], (struct sockaddr*)&address, (socklen_t*)&addrlen);
                    printf("Host disconnected, ip %s, port %d\n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
                    close(socks[fd]);
                    socks[fd] = -1;
                } else {
                    printf("Read from client_fd %d: %s\n", socks[fd], buffer );
                    // 这里可以处理读取到的数据
                }
            }
    }

    return 0;
}